package com.xp.flower.qsd.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.xp.flower.api.IUserService;
import com.xp.flower.common.ajax.AjaxError;
import com.xp.flower.common.ajax.AjaxResponse;
import com.xp.flower.common.dto.UserDTO;
import com.xp.flower.qsd.consts.WebConsts;
import com.xp.flower.qsd.utils.weixin.WeiXinGlobalConstants;
import com.xp.flower.qsd.utils.weixin.WeiXinUtils;

@RequestMapping("userController")
@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "goToLogin", method = RequestMethod.GET)
    public String goToLogin(Model model) {
        model.addAttribute("authLoginNotifyURL", WeiXinGlobalConstants.getProperties("authLoginNotifyURL"));
        return "qsd/login";
    }
    
    @RequestMapping(value = "auth", method = RequestMethod.GET)
    public String auth(HttpServletRequest request,Model model) throws Exception{
      //获取OAuth2.0请求后，服务器返回的code内容,这个code在接下来向微信服务请求用户信息的时候要用到
        String code = request.getParameter("code");
        
        
        JSONObject jsonResult = WeiXinUtils.getWeiXinLoginAccessTokenByCode(code);
        String accessToken = jsonResult.getString("access_token");
        String openid = jsonResult.getString("openid");
        
        //验证access_token是否有效
        //由于access_token有效期比较短，当access_token失效后，可以使用refresh_token进行刷新，refresh_token的有效期为30天。refresh_token失效后需要用户重新授权。
//        JSONObject validateResult = WeiXinUtils.validateWeiXinAccessToken(accessToken,openid);
        
        JSONObject weiXinUserInfo = WeiXinUtils.getWeiXinUserInfo(accessToken,openid);
        
        UserDTO userDTO = new UserDTO();
        userDTO.setHeadimgurl(weiXinUserInfo.getString("headimgurl"));
        userDTO.setOpenid(weiXinUserInfo.getString("openid"));
        userDTO.setNickname(weiXinUserInfo.getString("nickname"));
        
        
        userServiceImpl.insertUser(userDTO);
        
        request.getSession().setAttribute(WebConsts.USERINFO, userDTO);
        return "qsd/index";
        
    }
    
    @RequestMapping(value = "goToIndex", method = RequestMethod.GET)
    public String goToIndex() {
        return "qsd/index";
    }

    @RequestMapping(value = "loginValidate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse<UserDTO> loginValidate(HttpServletRequest request,
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password) {
        UserDTO userDTO = userServiceImpl.queryUserByUserNameAndPassword(username, password);
        AjaxResponse<UserDTO> response = null;
        if (null == userDTO) {
            response = new AjaxResponse<UserDTO>(AjaxError.LOGINERROR.getCode(), AjaxError.LOGINERROR.getMessage());
        } else {
            //TODO
            //这里可以重新封装userInfo,比如可以将用户权限放到userIfo
            request.getSession().setAttribute(WebConsts.USERINFO, userDTO);
            response = new AjaxResponse<UserDTO>(AjaxError.LOGINGSUCCESS.getCode(), AjaxError.LOGINGSUCCESS.getMessage());
        }
        return response;
    }
    
    //我的
    @RequestMapping(value = "goToWode", method = RequestMethod.GET)
    public String goToWode(@RequestParam(value = "userId", required = false)Long userId,Model model){
        model.addAttribute("userId", userId);
        return "qsd/wode";
    }
    
    
}
